package com.touchyourheart.web.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.brickred.socialauth.AuthProvider;
import org.brickred.socialauth.SocialAuthManager;
import org.brickred.socialauth.spring.bean.SocialAuthTemplate;
import org.brickred.socialauth.util.SocialAuthUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.touchyourheart.TouchYourHeartConstants;

@Controller
@RequestMapping("/social")
public class SocialController {

  private Logger LOG = LoggerFactory.getLogger(SocialController.class);

  @Autowired
  private SocialAuthTemplate socialAuthTemplate;

  @Autowired
  private SocialAuthManager socialAuthManager;

  @RequestMapping(value = "/id/{providerId}", method = { RequestMethod.GET })
  public String provider(@PathVariable String providerId, HttpServletRequest request) throws Exception {
    LOG.info("Getting Authentication URL for :" + providerId);
    String callbackURL = TouchYourHeartConstants.DOMAIN + "/social/callback";
    String url = socialAuthManager.getAuthenticationUrl(providerId, callbackURL);
    socialAuthTemplate.setSocialAuthManager(socialAuthManager);
    return "redirect:" + url;
  }

  @RequestMapping(value = "/callback", method = { RequestMethod.GET })
  public ModelAndView callback(final HttpServletRequest request) throws Exception {

    ModelAndView mv = new ModelAndView();
    SocialAuthManager manager = socialAuthTemplate.getSocialAuthManager();
    AuthProvider provider = manager.connect(SocialAuthUtil.getRequestParametersMap(request));
    LOG.info(ToStringBuilder.reflectionToString(provider.getUserProfile()));
    mv.addObject("profile", provider.getUserProfile());

    mv.setViewName("/register/test");

    return mv;

  }
  
}
